<template>
  <div style="overflow-y:auto">
    <ul style="padding-left:5px" class="tree">
      <tree-node :level="0" @push="push" @remove="remove" :ids="ids" v-for="(item,index) in datas" :key="index" :node="item"></tree-node>
    </ul>
  </div>
</template>
<script>
import linq from 'linq'
export default {
  data () {
    return {
      ids: this.value,
      datas: [],
      labels: []
    }
  },
  props: ['nodes', 'value', 'isNeedChangData'],
  components: {
    TreeNode: resolve => require(['./treeNode.vue'], resolve)
  },
  watch: {
    nodes: function (val) {
      this.datas = this.GetData(0, val)
    }
  },
  created () {
    this.datas = this.GetData(0, this.nodes)
  },
  methods: {
    GetData: function (id, arry = this.nodes) {
      let [vm, list] = [this, []]
      var childArry = this.GetParentArry(id, arry)
      if (childArry.length > 0) {
        for (var i in childArry) {
          let test = {
            entityCode: childArry[i].entityCode,
            entityTitle: childArry[i].entityTitle,
            children: vm.GetData(childArry[i].entityId, arry)
          }
          list.push(test)
        }
      }
      return list
    },
    GetParentArry: function (id, arry) {
      var newArry = []
      for (var i in arry) {
        if (arry[i].parentId === id) {
          newArry.push(arry[i])
        }
      }
      return newArry
    },
    push: function (val) {
      if (linq.from(this.ids).indexOf(val.id) < 0) {
        this.ids.push(val.id)
        this.labels.push(val.text)
        this.$emit('input', this.ids)
        this.$emit('update:labels', this.labels)
      }
    },
    remove: function (val) {
      let index = linq.from(this.ids).indexOf(val.id)
      if (index > -1) {
        this.ids.splice(index, 1)
        this.labels.splice(index, 1)
      }
      this.$emit('input', this.ids)
      this.$emit('update:labels', this.labels)
    },
  }
}
</script>
<style v-once scoped>
ul.tree ul {
  margin-left: 0;
}
ul.tree li {
  margin: 0;
  padding: 0;
  line-height: 40px;
  color: #222;
  border-top-right-radius: 0px;
  border-top-left-radius: 0px;
}
ul.tree .licheckbox {
  float: left;
  width: 20px;
}
.positions ul li:last-child {
  border-bottom: none !important;
}
.positions {
  border-right: 1px solid;
}
</style>